package no.nordicsemi.android.nrfmesh.node;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import no.nordicsemi.android.nrfmesh.R;
import no.nordicsemi.android.nrfmesh.domain.Wave;

public class WaveformSegmentFragment extends Fragment {

    public static WaveformSegmentFragment newInstance(int index) {
        WaveformSegmentFragment fragment = new WaveformSegmentFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        fragment.setArguments(args);
        return fragment;
    }

    // === Waveform settings ===
    // 波形设置
    private Button btnSegmentRepeatMinus, btnSegmentRepeatPlus;
    private TextView tvSegmentRepeatValue;

    private Button   btnDurationMinus, btnDurationPlus;
    private TextView tvDurationValue;

    private Spinner  spinnerWaveformType;

    private Button   btnPulseWidthMinus, btnPulseWidthPlus;
    private TextView tvPulseWidthValue;

    private Button   btnFrequencyMinus, btnFrequencyPlus;
    private TextView tvFrequencyValue;

    private Button   btnWaveformRepeatMinus, btnWaveformRepeatPlus;
    private TextView tvWaveformRepeatValue;

    private Button   btnGearMinus, btnGearPlus;
    private TextView tvGearValue;
    private Button   btnTimeMinus, btnTimePlus;
    private TextView tvTimeValue;
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d("DEBUG", "Fragment loaded: index=" + getArguments().getInt("index", -1));
        tvSegmentRepeatValue = view.findViewById(R.id.tvSegmentRepeatValue);
        tvDurationValue = view.findViewById(R.id.tvDurationValue);
        tvGearValue = view.findViewById(R.id.tvGearValue);
        spinnerWaveformType = view.findViewById(R.id.spinnerWaveformType);
        tvPulseWidthValue = view.findViewById(R.id.tvPulseWidthValue);
        tvFrequencyValue = view.findViewById(R.id.tvFrequencyValue);
        tvWaveformRepeatValue = view.findViewById(R.id.tvWaveformRepeatValue);


        btnSegmentRepeatMinus = view.findViewById(R.id.btnSegmentRepeatMinus);
        tvSegmentRepeatValue  = view.findViewById(R.id.tvSegmentRepeatValue);
        btnSegmentRepeatPlus  = view.findViewById(R.id.btnSegmentRepeatPlus);

        btnDurationMinus = view.findViewById(R.id.btnDurationMinus);
        tvDurationValue  = view.findViewById(R.id.tvDurationValue);
        btnDurationPlus  = view.findViewById(R.id.btnDurationPlus);

        spinnerWaveformType = view.findViewById(R.id.spinnerWaveformType);

        btnPulseWidthMinus = view.findViewById(R.id.btnPulseWidthMinus);
        tvPulseWidthValue  = view.findViewById(R.id.tvPulseWidthValue);
        btnPulseWidthPlus  = view.findViewById(R.id.btnPulseWidthPlus);

        btnFrequencyMinus = view.findViewById(R.id.btnFrequencyMinus);
        tvFrequencyValue  = view.findViewById(R.id.tvFrequencyValue);
        btnFrequencyPlus  = view.findViewById(R.id.btnFrequencyPlus);

        btnWaveformRepeatMinus = view.findViewById(R.id.btnWaveformRepeatMinus);
        tvWaveformRepeatValue  = view.findViewById(R.id.tvWaveformRepeatValue);
        btnWaveformRepeatPlus  = view.findViewById(R.id.btnWaveformRepeatPlus);


        btnSegmentRepeatMinus.setOnClickListener(v ->{
            Toast.makeText(getContext(), "点击 +", Toast.LENGTH_SHORT).show();
            adjustValue(tvSegmentRepeatValue, -1);
        });
        btnSegmentRepeatPlus.setOnClickListener(v -> adjustValue(tvSegmentRepeatValue, +1));

        btnDurationMinus.setOnClickListener(v -> adjustValue(tvDurationValue, -1));
        btnDurationPlus.setOnClickListener(v -> adjustValue(tvDurationValue, +1));

        btnPulseWidthMinus.setOnClickListener(v -> adjustValue(tvPulseWidthValue, -10));
        btnPulseWidthPlus.setOnClickListener(v -> adjustValue(tvPulseWidthValue, +10));

        btnFrequencyMinus.setOnClickListener(v -> adjustValue(tvFrequencyValue, -1));
        btnFrequencyPlus.setOnClickListener(v -> adjustValue(tvFrequencyValue, +1));

        btnWaveformRepeatMinus.setOnClickListener(v -> adjustValue(tvWaveformRepeatValue, -1));
        btnWaveformRepeatPlus.setOnClickListener(v -> adjustValue(tvWaveformRepeatValue, +1));

        // 初始化 Spinner（从 string-array 资源加载）
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                requireContext(),
                R.array.wave_type_options,
                android.R.layout.simple_spinner_item
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerWaveformType.setAdapter(adapter);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_waveform_segment, container, false);
    }

    private void adjustValue(final TextView tv, final int delta) {
        String rawText = tv.getText().toString();
        String unit = rawText.replaceAll("[0-9]", ""); // 提取单位（如 s、ms、Hz）
        String numberOnly = rawText.replaceAll("[^0-9]", "");

        int currentValue = numberOnly.isEmpty() ? 0 : Integer.parseInt(numberOnly);
        int newValue = currentValue + delta;

        // 设置通用的范围限制（你可按需改成个别限制）
        if (newValue < 0) newValue = 0;
        if (newValue > 9999) newValue = 9999;

        // 更新 TextView
        tv.setText(newValue + unit);
    }



    public Wave getWave() {
        Wave wave = new Wave();

        wave.setCount("1"); // 从 args 或 position

//        wave.setRepeat(getNumberFromText(tvSegmentRepeatValue));
        wave.setTime(getNumberFromText(tvDurationValue)); // 转换成单位为 *500ms 可在外部统一处理
        wave.setGear(getNumberFromText(tvGearValue));
        String selectedCode = getSelectedWaveTypeCode();
        Log.d("DEBUG", "Waveform type selected label=" + spinnerWaveformType.getSelectedItem() + ", code=" + selectedCode);
        wave.setType(selectedCode);
        wave.setPusle_witdth(getNumberFromText(tvPulseWidthValue));
        wave.setFrequence(getNumberFromText(tvFrequencyValue));
//        wave.setCount(getNumberFromText(tvWaveformRepeatValue));

        return wave;
    }

    private String getNumberFromText(TextView tv) {
        return tv.getText().toString().replaceAll("[^0-9]", "");
    }

    // 根据 Spinner 位置映射到 "1".."9"
    private String getSelectedWaveTypeCode() {
        if (spinnerWaveformType == null || spinnerWaveformType.getAdapter() == null) {
            return "0";
        }
        int pos = spinnerWaveformType.getSelectedItemPosition();
        return pos >= 0 ? String.valueOf(pos + 1) : "0";
    }
}